package com.yyy;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author yyy
 * @Date 2020-09-23 23:58
 * @Email yangyouyuhd@163.com
 */
public class tryWork {
    public static void main(String[] args) {

        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                new Thread(()->{
                    for (int j = 0; j < 100; j++) {
                        if(tryWork()){
//                        doIdle();
                        }
                    }
                }).start();
            }
        }).start();

        while (atomicBoolean.get() > -1){
            try {
                Thread.sleep( 10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(atomicBoolean.get());
        }

    }

    static AtomicInteger atomicBoolean = new AtomicInteger(0);

    public static void doIdle() {
        atomicBoolean.set(atomicBoolean.get() - 1);
    }

    /**
     * 试图进入工作状态
     *
     * @return
     */
    public static boolean tryWork() {
        int  isIdle = atomicBoolean.get();
        do {
            isIdle = atomicBoolean.get();
        }while (!atomicBoolean.compareAndSet(isIdle,++isIdle));

//        boolean b = atomicBoolean.compareAndSet(isIdle, isIdle++);
//        return b;
        return true;
    }
}
